package com.example.sams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.sams.domain.enums.CourseStatus;
import com.example.sams.domain.po.*;
import com.example.sams.domain.vo.CourseVO;
import com.example.sams.domain.vo.TimeSlotVO;
import com.example.sams.mapper.CoursesMapper;
import com.example.sams.mapper.TeachersMapper;
import com.example.sams.service.*;
import com.example.sams.utils.ResultUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程表 服务实现类
 * </p>
 *
 * @author jinghong
 * @since 2025-11-04
 */
@Service
public class CoursesServiceImpl extends ServiceImpl<CoursesMapper, Courses> implements ICoursesService {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private TeachersMapper teachersMapper;

    @Autowired
    private ITimeSlotsService timeSlotsService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ResultUtil getApprovedCourses() {
        // 1. 查询所有已审核通过的课程
        LambdaQueryWrapper<Courses> courseWrapper = new LambdaQueryWrapper<>();
        courseWrapper.eq(Courses::getStatus, CourseStatus.approved);
        List<Courses> courses = this.list(courseWrapper);

        // 2. 构建课程VO列表
        List<CourseVO> courseVOList = new ArrayList<>();
        for (Courses course : courses) {
            // 查询教师信息
            String teacherName = "未知教师";
            if (course.getTeacherId() != null) {
                Teachers teacher = teachersMapper.selectById(course.getTeacherId());
                if (teacher != null) {
                    Users teacherUser = usersService.getById(teacher.getUserId());
                    if (teacherUser != null) {
                        teacherName = teacherUser.getName();
                    }
                }
            }

            // 查询时间段信息
            List<TimeSlotVO> timeSlotVOList = new ArrayList<>();
            LambdaQueryWrapper<TimeSlots> timeSlotWrapper = new LambdaQueryWrapper<>();
            timeSlotWrapper.eq(TimeSlots::getCourseId, course.getId());
            List<TimeSlots> timeSlots = timeSlotsService.list(timeSlotWrapper);

            for (TimeSlots timeSlot : timeSlots) {
                TimeSlotVO timeSlotVO = TimeSlotVO.builder()
                        .dayOfWeek(timeSlot.getDayOfWeek())
                        .start(timeSlot.getStart() != null ? timeSlot.getStart().format(DateTimeFormatter.ofPattern("HH:mm")) : null)
                        .end(timeSlot.getEnd() != null ? timeSlot.getEnd().format(DateTimeFormatter.ofPattern("HH:mm")) : null)
                        .room(timeSlot.getRoom())
                        .startWeek(timeSlot.getStartWeek())
                        .endWeek(timeSlot.getEndWeek())
                        .build();

                // 解析weeks JSON字符串为List<Integer>
                if (timeSlot.getWeeks() != null && !timeSlot.getWeeks().isEmpty()) {
                    try {
                        List<Integer> weeks = objectMapper.readValue(timeSlot.getWeeks(), new TypeReference<List<Integer>>() {});
                        timeSlotVO.setWeeks(weeks);
                    } catch (Exception e) {
                        // 如果解析失败，忽略weeks字段
                    }
                }

                timeSlotVOList.add(timeSlotVO);
            }

            CourseVO courseVO = CourseVO.builder()
                    .id(course.getId())
                    .name(course.getName())
                    .teacherName(teacherName)
                    .credit(course.getCredit())
                    .capacity(course.getCapacity())
                    .enrolledCount(course.getEnrolledCount())
                    .timeSlots(timeSlotVOList)
                    .build();

            courseVOList.add(courseVO);
        }

        return ResultUtil.success(courseVOList);
    }

    @Override
    public ResultUtil searchCourses(String query) {
        // 1. 如果查询关键词为空，返回所有课程
        if (query == null || query.trim().isEmpty()) {
            return getApprovedCourses();
        }

        String lowerQuery = query.trim().toLowerCase();

        // 2. 查询所有课程（包括待审核和已审核的）
        List<Courses> allCourses = this.list();

        // 3. 构建课程VO列表
        List<CourseVO> courseVOList = new ArrayList<>();
        for (Courses course : allCourses) {
            // 查询教师信息
            String teacherName = "未知教师";
            String teacherAccount = "";
            if (course.getTeacherId() != null) {
                Teachers teacher = teachersMapper.selectById(course.getTeacherId());
                if (teacher != null) {
                    Users teacherUser = usersService.getById(teacher.getUserId());
                    if (teacherUser != null) {
                        teacherName = teacherUser.getName();
                        teacherAccount = teacher.getAccount();
                    }
                }
            }

            // 3.1 匹配课程名称
            boolean matchCourseName = course.getName() != null &&
                    course.getName().toLowerCase().contains(lowerQuery);

            // 3.2 匹配教师姓名
            boolean matchTeacherName = teacherName.toLowerCase().contains(lowerQuery);

            // 3.3 匹配教师工号
            boolean matchTeacherAccount = teacherAccount != null &&
                    teacherAccount.toLowerCase().contains(lowerQuery);

            // 如果都不匹配，跳过
            if (!matchCourseName && !matchTeacherName && !matchTeacherAccount) {
                continue;
            }

            // 查询时间段信息
            List<TimeSlotVO> timeSlotVOList = new ArrayList<>();
            LambdaQueryWrapper<TimeSlots> timeSlotWrapper = new LambdaQueryWrapper<>();
            timeSlotWrapper.eq(TimeSlots::getCourseId, course.getId());
            List<TimeSlots> timeSlots = timeSlotsService.list(timeSlotWrapper);

            for (TimeSlots timeSlot : timeSlots) {
                TimeSlotVO timeSlotVO = TimeSlotVO.builder()
                        .dayOfWeek(timeSlot.getDayOfWeek())
                        .start(timeSlot.getStart() != null ? timeSlot.getStart().format(DateTimeFormatter.ofPattern("HH:mm")) : null)
                        .end(timeSlot.getEnd() != null ? timeSlot.getEnd().format(DateTimeFormatter.ofPattern("HH:mm")) : null)
                        .room(timeSlot.getRoom())
                        .startWeek(timeSlot.getStartWeek())
                        .endWeek(timeSlot.getEndWeek())
                        .build();

                // 解析weeks JSON字符串为List<Integer>
                if (timeSlot.getWeeks() != null && !timeSlot.getWeeks().isEmpty()) {
                    try {
                        List<Integer> weeks = objectMapper.readValue(timeSlot.getWeeks(), new TypeReference<List<Integer>>() {});
                        timeSlotVO.setWeeks(weeks);
                    } catch (Exception e) {
                        // 如果解析失败，忽略weeks字段
                    }
                }

                timeSlotVOList.add(timeSlotVO);
            }

            CourseVO courseVO = CourseVO.builder()
                    .id(course.getId())
                    .name(course.getName())
                    .teacherName(teacherName)
                    .credit(course.getCredit())
                    .capacity(course.getCapacity())
                    .enrolledCount(course.getEnrolledCount())
                    .status(course.getStatus())
                    .timeSlots(timeSlotVOList)
                    .build();

            courseVOList.add(courseVO);
        }

        return ResultUtil.success(courseVOList);
    }
}
